import Api from "../lib/Api"
import wx from "weixin-js-sdk"

const DEFAULT_FN = n => n
const DEFAULT_OPTIONS = {
  link: window.location.href,
  type: "link",
  dataUrl: "",
  success: DEFAULT_FN,
  error: DEFAULT_FN,
  cancel: DEFAULT_FN,
  debug: GD.URLparams.wxdebug || false,
  apiList: ["onMenuShareTimeline", "onMenuShareAppMessage"],
  doc_id: 0
}

export default function (params = {}) {
  let { title, desc, img: imgUrl, link, success, error, cancel, type, dataUrl, debug, apiList, doc_id } = {
    ...DEFAULT_OPTIONS,
    ...params
  }

  Api.require(
    "share",
    {
      ct: "user",
      ac: "ajax_ticket",
      url: encodeURIComponent(link)
    },
    {
      domain: `//${window.aList[ENV]}`,
      dataType: "jsonp",
      urlModel: 1,
      debug
    }
  )
    .then(res => {
      if (!res.data) return console.warn("get share config error!", res)

      let {
        app_id: appId,
        noncestr: nonceStr,
        signature,
        timestamp,
        sign_url: link
      } = res.data.info
      let shareMsg = {
        title,
        desc,
        link,
        imgUrl,
        type,
        dataUrl,
        success,
        cancel
      }

      wx.config({
        debug,
        appId,
        timestamp,
        nonceStr,
        signature,
        jsApiList: ["checkJsApi", "previewImage", ...apiList]
      });

      wx.error(error);

      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: [...apiList, "previewImage"],
        })
        apiList.forEach(api => wx[api]({
          ...shareMsg,
          success() {
            typeof shareMsg.success==='function'&&shareMsg.success();
            Api.require('', {
              ct: 'doc',
              ac: 'share_doc',
              doc_id,
              url: link
            }).then(res=>{})
          }
        }));
      })
    })
    .catch(e => {
      console.log("share.error:", e)
    })
}
